package com.jpsl.core.util;

import com.jpsl.core.reflection.PropertiesMapper;

import java.util.Objects;

/**
 * 属性工具
 *
 * @author 懒王猫
 */
public class PropertiesUtil {

    @SuppressWarnings("unchecked")
    public static <T> T clone(T t) {
        try {
            T cloned = (T) t.getClass().newInstance();
            new PropertiesMapper(t, cloned).map();
            return cloned;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 深度属性复制
     *
     * @param source 源
     * @param target 目标
     */
    public static void deepCopyProperties(Object source, Object target) {
        copyProperties(source, target, true, false);
    }

    /**
     * 属性复制
     *
     * @param source 源
     * @param target 目标
     */
    public static void copyProperties(Object source, Object target) {
        copyProperties(source, target, false, false);
    }

    /**
     * 属性复制
     *
     * @param source 源
     * @param target 目标
     * @param deepCopy 深度复制
     * @param ignoreSrcNullValue 是否忽略空值
     */
    public static void copyProperties(Object source, Object target, boolean deepCopy, boolean ignoreSrcNullValue) {
        PropertiesMapper mapper = new PropertiesMapper(source, target).setDeepMapping(deepCopy);
        PropertiesMapper.Config config = mapper.getConfig();
        if (ignoreSrcNullValue) {
            config.setDefaultSrcPropertyFilter(Objects::nonNull);
        }
        mapper.map();
    }

    /**
     * 属性复制
     *
     * @param source 源
     * @param target 目标
     * @param ignoreSrcProperties 忽略复制的源属性名称
     */
    public static void copyProperties(Object source, Object target, String... ignoreSrcProperties) {
        PropertiesMapper mapper = new PropertiesMapper(source, target);
        PropertiesMapper.Config config = mapper.getConfig();
        if (CollectionUtil.isNotEmpty(ignoreSrcProperties)) {
            for (String ignoreSrcProperty : ignoreSrcProperties) {
                config.addSrcPropertyFilter(ignoreSrcProperty, srcVal -> false);
            }
        }
        mapper.map();
    }


}
